package interpreter;

import java.util.List;

import ast.Body;
import ast.Lambda;

public class LambdaCallable implements Callable {

	private Lambda lambda;
	private Interpreter interpreter;
	private SymbolTable symbolTable;

	public LambdaCallable(Lambda lambda, Interpreter i, SymbolTable table) {
		this.lambda = lambda;
		this.interpreter = i;
		this.symbolTable = table;
	}

	@Override
	public Object call(List<Object> arguments) {
		symbolTable.pushScope();
		bind(arguments);
		Object result = evaluate(lambda.getBody());
		symbolTable.popScope();
		return result;
	}

	private void bind(List<Object> arguments) {
		// TODO bind list if present
		for (int i = 0; i < arguments.size(); i++)
			symbolTable.put(new Symbol(parameterName(i), arguments.get(i)));
	}

	private String parameterName(int i) {
		return lambda.getArguments().get(i).getIdentifier();
	}

	private Object evaluate(Body body) {
		return interpreter.evaluate(body);
	}
}
